package com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPersonalAnalysis.aibkAnalysisGCT

import android.graphics.Color
import android.graphics.Paint
import android.graphics.Typeface
import android.os.Bundle
import android.view.*
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.adapter.SpacesItemDecoration
import com.lancoo.znbkxx.teacher.adapter.TextFlowAdapter
import com.lancoo.znbkxx.teacher.aibkTestCoach.kBase.KBaseFragment
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.entity.PaperPerAnalysisInfor
import com.lancoo.znbkxx.teacher.model.AnswerInfo
import com.lancoo.znbkxx.teacher.model.TextInfo
import com.lancoo.znbkxx.teacher.utils.DensityUtils
import com.lancoo.znbkxx.teacher.utils.HtmlUtils
import com.lancoo.znbkxx.teacher.utils.ToolsUtils
import kotlinx.android.synthetic.main.aibk_include_question_information_view.view.*
import kotlinx.android.synthetic.main.fmt_gct.*
import kotlin.math.abs

class AnalysisFragmentGct(
        val activity: AppCompatActivity,
        val paperPerAnalysisInfor: PaperPerAnalysisInfor,
        val index_A: Int,
        val index_B: Int
) : KBaseFragment() {
    private var questContent: String = ""
    private val textInfoList = mutableListOf<TextInfo>()
    private lateinit var adapter: TextFlowAdapter
    private lateinit var analysisAdapter: AnalysisGctAdapter
    private val answerInfoList = mutableListOf<AnswerInfo>()
    private var genreType = 0
    private val answerArea = mutableListOf<String>()
    private val isScanAnswer by lazy { paperPerAnalysisInfor.TypeList[index_A].QuesAnswerList[index_B].IsScanAnswer }


    override fun createLayout(): Int {
        return R.layout.fmt_gct
    }

    override fun initView(view: View?) {
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        genreType = paperPerAnalysisInfor.TypeList[index_A].QuesDetailList[index_B].GenreType.toInt()
        if (genreType != 3) {
            val answerAreaList = paperPerAnalysisInfor.TypeList[index_A].QuesDetailList[index_B].ModelAnswerAreaList
            for (i in answerAreaList.indices) {
                val area = answerAreaList[i].answerArea.split("-")[0]
                answerArea.add(area)
            }
        }
        questContent = paperPerAnalysisInfor.TypeList[index_A].QuesDetailList[index_B].QuesLeaderContent
        textInfoList.addAll(
                paperPerAnalysisInfor.TypeList[index_A].QuesDetailList[index_B].ModelTextInfoList)
        answerInfoList.addAll(
                paperPerAnalysisInfor.TypeList[index_A].QuesDetailList[index_B].ModelAnswerInfoList)
        val subChildItemBeanXList = paperPerAnalysisInfor.TypeList[index_A].QuesAnswerList[index_B].ChildAnswerList[0].ItemList
        for (s in answerInfoList.indices) {
            val itemAnswers = answerInfoList[s].answer.split("$|")
            val stuAnswers = subChildItemBeanXList[s].StuAnswer.split("@|")
            var stuAnswer: String
            var itemAnswer: String
            //有作答
            if (stuAnswers.size == 2) {
                val stuAnswerInfo = stuAnswers[0].split("*|")
                val stuAnswerIndex = stuAnswerInfo[0]
                val stuAnswerType = stuAnswerInfo[1]
                val i = stuAnswerIndex.toInt()
                if (itemAnswers.contains(stuAnswers[0])) {
                    stuAnswer = if (stuAnswerType != "0") {
                        stuAnswerInfo[2]
                    } else {
                        ""
                    }
                    textInfoList[i].stuAnswer = stuAnswer
                    textInfoList[i].stuType = stuAnswerType.toInt()
                    textInfoList[i].color = 1
                } else {
                    val itemAnswerInfo = itemAnswers[0].split("*|")
                    val j = Integer.parseInt(itemAnswerInfo[0])
                    //不是删除
                    itemAnswer = if (itemAnswerInfo[1] != "0") {
                        itemAnswerInfo[2]
                    } else {
                        ""
                    }
                    //不是删除
                    stuAnswer = if (stuAnswerType != "0") {
                        stuAnswerInfo[2]
                    } else {
                        "删除" + textInfoList[i].text
                    }
                    //位置正确，答案错误
                    if (i == j && stuAnswerType == itemAnswerInfo[1]) {
                        textInfoList[i].answer = itemAnswer
                        textInfoList[i].type = itemAnswerInfo[1].toInt()
                        textInfoList[i].stuType = stuAnswerType.toInt()
                        textInfoList[i].stuAnswer = stuAnswer
                        textInfoList[i].color = 0
                    } else {
                        textInfoList[i].stuAnswer = stuAnswer
                        textInfoList[i].stuType = stuAnswerType.toInt()
                        textInfoList[i].color = 2
                        if (j > 0 && textInfoList[j - 1].type != 3) {
                            textInfoList[j].answer = itemAnswer
                            textInfoList[j].type = itemAnswerInfo[1].toInt()
                            textInfoList[j].color = 0
                        } else if (j == 0) {
                            textInfoList[j].answer = itemAnswer
                            textInfoList[j].type = itemAnswerInfo[1].toInt()
                            textInfoList[j].color = 0
                        }
                    }
                }
            } else {
                for (a in itemAnswers.indices) {
                    val itemAnswerInfo = itemAnswers[a].split("*|")
                    val i = Integer.parseInt(itemAnswerInfo[0])
                    var itemAnswer: String
                    //不是删除
                    itemAnswer = if (itemAnswerInfo[1] != "0") {
                        itemAnswerInfo[2]
                    } else {
                        ""
                    }
                    if (i == 0) {
                        textInfoList[i].type = Integer.valueOf(itemAnswerInfo[1])
                        textInfoList[i].answer = itemAnswer
                        textInfoList[i].color = 0
                    } else if (i > 0 && i < textInfoList.size - 1) {
                        if (!isSameAnswer(textInfoList[i - 1], itemAnswerInfo) && !isSameAnswer(
                                        textInfoList[i + 1], itemAnswerInfo)) {
                            textInfoList[i].type = Integer.valueOf(itemAnswerInfo[1])
                            textInfoList[i].answer = itemAnswer
                            textInfoList[i].color = 0
                        }
                    }
//                    else {
//                        if (!isSameAnswer(textInfoList[i - 1], itemAnswerInfo)) {
//                            textInfoList[i].type = Integer.valueOf(itemAnswerInfo[1])
//                            textInfoList[i].answer = itemAnswer
//                            textInfoList[i].color = 0
//                        }
//                    }
                }
            }
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        //是否显示来源
        var resource = paperPerAnalysisInfor.TypeList[index_A].QuesDetailList[index_B].Resource
        if (resource.isEmpty()) {
            IncludeQuesInformationView.visibility = View.GONE
        } else {
            IncludeQuesInformationView.visibility = View.VISIBLE
            IncludeQuesInformationView.TvSourceFrom.text = "来源: $resource"
            //隐藏试题准确率
            IncludeQuesInformationView.TvScoreRate.visibility = View.GONE
        }

        tv_leader.text = questContent
        val itemList = paperPerAnalysisInfor.TypeList[index_A].QuesAnswerList[index_B].ChildAnswerList[0].ItemList
        val analysisList = paperPerAnalysisInfor.TypeList[index_A].QuesDetailList[index_B].ChildList[0].ItemList
        val stuAnswerList =
                paperPerAnalysisInfor.TypeList[index_A].QuesAnswerList[index_B].ChildAnswerList[0].StuAnswer
        val sortIndexList = paperPerAnalysisInfor.TypeList[index_A].QuesList[index_B].SortIndexList
        val genrelID = paperPerAnalysisInfor.TypeList[index_A].GenreID
        analysisAdapter = AnalysisGctAdapter(isScanAnswer,
                genrelID,
                stuAnswerList,
                sortIndexList,
                analysisList,
                itemList)
        val hashMap = hashMapOf<String, Int>()
        hashMap[SpacesItemDecoration.TOP_SPACE] = DensityUtils.dp2px(context, 10f)
        rv_analysis.addItemDecoration(SpacesItemDecoration(hashMap))
        rv_analysis.layoutManager = LinearLayoutManager(requireContext())
        rv_analysis.adapter = analysisAdapter
        val mLayoutInflater = LayoutInflater.from(context)
        adapter = TextFlowAdapter(textInfoList, mLayoutInflater)
        fl.setAdapter(adapter)
        for (i in textInfoList.indices) {
            val textInfo = textInfoList[i]
            val child: View = fl.getChildAt(i)
            val tvText = child.findViewById<TextView>(R.id.tv_text)
            if (genreType != 1) {
                tvText.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
            } else {
                for (j in answerArea.indices) {
                    if (i == Integer.valueOf(answerArea[j])) {
                        tvText.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
                        tvText.paint.flags = Paint.UNDERLINE_TEXT_FLAG
                    }
                }
            }
            if (!isScanAnswer) {
                val tvType = child.findViewById<TextView>(R.id.tv_type)
                child.viewTreeObserver.addOnGlobalLayoutListener(object :
                        ViewTreeObserver.OnGlobalLayoutListener {
                    override fun onGlobalLayout() {
                        val width = ToolsUtils.getViewWidth(child)
                        val x = child.x
                        val y = child.y
                        drawIndex(i, fl_layout, x, y, width)
                        drawAnswer(fl_layout, i, x, y, width, tvType, textInfo, child)
                        child.viewTreeObserver.removeOnGlobalLayoutListener(this)
                    }
                })
            }
        }
    }

    /*是否是相同的前增后增*/
    private fun isSameAnswer(textInfo: TextInfo,
                             itemAnswerInfo: List<String>): Boolean {
        val type = textInfo.type
        val type2 = Integer.valueOf(itemAnswerInfo[1])
        return if (type != -1 && type2 != -1) {
            abs(type - type2) == 1 && textInfo.answer == itemAnswerInfo[2]
        } else {
            false
        }
    }

    private fun drawIndex(position: Int, ll: ViewGroup, x: Float, y: Float, width: Int) {
        //绘制编号
        if (genreType == 2) {
            answerArea.forEachIndexed { index, it ->
                if (it.toInt() == position) {
                    val tvIndex = TextView(getActivity())
                    tvIndex.layoutParams = LinearLayout.LayoutParams(
                            DensityUtils.dp2px(getActivity(), 12f),
                            DensityUtils.dp2px(getActivity(), 12f))
                    tvIndex.textSize = 11f
                    tvIndex.text = (index + 1).toString()
                    tvIndex.includeFontPadding = false
                    tvIndex.setTextColor(Color.WHITE)
                    tvIndex.background = ContextCompat.getDrawable(requireContext(),
                            R.drawable.bg_gctindex)
                    tvIndex.gravity = Gravity.CENTER
                    ll.addView(tvIndex)
                    tvIndex.x = x + DensityUtils.dp2px(
                            getActivity(), 10f)
                    tvIndex.y = y + DensityUtils.dp2px(
                            getActivity(), 18f)
                }
            }
        }
    }

    /*绘制答案*/
    private fun drawAnswer(ll: ViewGroup, finalI: Int, x: Float, y: Float,
                           width: Int, tvType: TextView,
                           textInfo: TextInfo,
                           child: View) {
        val type = textInfo.type
        val stuType = textInfo.stuType
        val answer = textInfo.answer
        val stuAnswer = textInfo.stuAnswer
        val color = textInfo.color
        val tvAnswer = TextView(getActivity())
        tvAnswer.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT)
        tvAnswer.textSize = 11f
        ll.addView(tvAnswer)
        tvType.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT)
        val line = child.findViewById<View>(R.id.v_line)
        //未作答
        if (stuAnswer.isEmpty() && answer.isNotEmpty()) {
            tvType.setTextColor(Color.parseColor("#ff0000"))
            line.setBackgroundColor(Color.parseColor("#ff0000"))
            if (type == 0) {
                tvType.visibility = View.INVISIBLE
                line.visibility = View.VISIBLE
            } else {
                tvAnswer.text = HtmlUtils.setText(
                        "<font color= '#ff0000'>$answer</font><font color= '#c0c0c0'>(未找出)</font>")
                tvType.visibility = View.VISIBLE
                when (type) {
                    1 -> {
                        val tvWidth = ToolsUtils.getViewWidth(tvAnswer)
                        val RalX = x + width / 2 - (tvWidth shr 1) + DensityUtils.dp2px(
                                requireActivity(), 20f)
                        if (RalX < 0) {
                            tvAnswer.x = 10f
                        } else {
                            tvAnswer.x = RalX
                        }
                        tvAnswer.y = y + DensityUtils.dp2px(getActivity(), 5f)
                        tvType.gravity = Gravity.CENTER
                        tvType.text = "/"
                    }
                    2 -> {
                        val tvWidth = ToolsUtils.getViewWidth(tvAnswer)
                        tvAnswer.paint.flags = Paint.UNDERLINE_TEXT_FLAG
                        val RalX = x - tvWidth + DensityUtils.dp2px(requireActivity(),
                                20f)
                        if (RalX < 0) {
                            tvAnswer.x = 10f
                        } else {
                            tvAnswer.x = RalX
                        }
                        tvAnswer.y = y + DensityUtils.dp2px(getActivity(), 5f)
                        tvType.gravity = Gravity.START
                        tvType.text = "\\"
                    }
                    3 -> {
                        val tvWidth = ToolsUtils.getViewWidth(tvAnswer)
                        val svWidth = dsv.width
                        tvAnswer.paint.flags = Paint.UNDERLINE_TEXT_FLAG
                        val RalX = x + width + DensityUtils.dp2px(requireActivity(), 20f)
                        if (RalX + tvWidth > svWidth) {
                            tvAnswer.x = svWidth - tvWidth - 10.toFloat()
                        } else {
                            tvAnswer.x = RalX
                        }
                        tvAnswer.y = y + DensityUtils.dp2px(getActivity(), 5f)
                        tvType.gravity = Gravity.END
                        tvType.text = "/"
                    }
                }
            }
        } else if (color == 0) {
            tvType.setTextColor(Color.parseColor("#ff0000"))
            line.setBackgroundColor(Color.parseColor("#ff0000"))
            when (type) {
                0 -> {
                    tvType.visibility = View.INVISIBLE
                    line.visibility = View.VISIBLE
                }
                1 -> {
                    tvAnswer.text = HtmlUtils.setText(
                            "<font color= '#ff0000'>$answer</font><font color= '#c0c0c0'>($stuAnswer)</font>")
                    val tvWidth = ToolsUtils.getViewWidth(tvAnswer)
                    val RalX = x + width / 2 - (tvWidth shr 1) + DensityUtils.dp2px(
                            requireActivity(), 20f)
                    if (RalX < 0) {
                        tvAnswer.x = 10f
                    } else {
                        tvAnswer.x = RalX
                    }
                    tvAnswer.y = y + DensityUtils.dp2px(getActivity(), 5f)
                    tvType.gravity = Gravity.CENTER
                    tvType.text = "/"
                }
                2 -> {
                    tvAnswer.text = HtmlUtils.setText(
                            "<font color= '#ff0000'>$answer</font><font color= '#c0c0c0'>(前增加$stuAnswer)</font>")
                    val tvWidth = ToolsUtils.getViewWidth(tvAnswer)
                    tvAnswer.paint.flags = Paint.UNDERLINE_TEXT_FLAG
                    val RalX = x - tvWidth + DensityUtils.dp2px(requireActivity(), 20f)
                    if (RalX < 0) {
                        tvAnswer.x = 10f
                    } else {
                        tvAnswer.x = RalX
                    }
                    tvAnswer.y = y + DensityUtils.dp2px(getActivity(), 5f)
                    tvType.gravity = Gravity.START
                    tvType.text = "\\"
                }
                3 -> {
                    tvAnswer.text = HtmlUtils.setText(
                            "<font color= '#ff0000'>$answer</font><font color= '#c0c0c0'>(后增加$stuAnswer)</font>")
                    val tvWidth = ToolsUtils.getViewWidth(tvAnswer)
                    val svWidth = dsv.width
                    tvAnswer.paint.flags = Paint.UNDERLINE_TEXT_FLAG
                    val RalX = x + tvWidth + DensityUtils.dp2px(requireActivity(), 26f)
                    if (RalX + tvWidth > svWidth) {
                        tvAnswer.x = svWidth - tvWidth - 10.toFloat()
                    } else {
                        tvAnswer.x = RalX
                    }
                    tvAnswer.y = y + DensityUtils.dp2px(getActivity(), 5f)
                    tvType.gravity = Gravity.END
                    tvType.text = "/"
                }
            }
        } else {
            if (color == 1) {
                tvType.setTextColor(Color.parseColor("#1ab600"))
                tvAnswer.setTextColor(Color.parseColor("#1ab600"))
                line.setBackgroundColor(Color.parseColor("#1ab600"))
            } else if (color == 2) {
                tvType.setTextColor(Color.parseColor("#00afff"))
                tvAnswer.setTextColor(Color.parseColor("#00afff"))
                line.setBackgroundColor(Color.parseColor("#00afff"))
            }
            when (stuType) {
                0 -> {
                    tvType.visibility = View.INVISIBLE
                    line.visibility = View.VISIBLE
                }
                1 -> {
                    tvAnswer.text = stuAnswer
                    val tvWidth = ToolsUtils.getViewWidth(tvAnswer)
                    val RalX = x + width / 2 - (tvWidth shr 1) + DensityUtils.dp2px(
                            requireActivity(), 20f)
                    if (RalX < 0) {
                        tvAnswer.x = 10f
                    } else {
                        tvAnswer.x = RalX
                    }
                    tvAnswer.y = y + DensityUtils.dp2px(getActivity(), 5f)
                    tvType.gravity = Gravity.CENTER
                    tvType.text = "/"
                }
                2 -> {
                    tvAnswer.text = stuAnswer
                    val tvWidth = ToolsUtils.getViewWidth(tvAnswer)
                    tvAnswer.paint.flags = Paint.UNDERLINE_TEXT_FLAG
                    val RalX = x - tvWidth + DensityUtils.dp2px(requireActivity(), 20f)
                    if (RalX < 0) {
                        tvAnswer.x = 10f
                    } else {
                        tvAnswer.x = RalX
                    }
                    tvAnswer.y = y + DensityUtils.dp2px(getActivity(), 5f)
                    tvType.gravity = Gravity.START
                    tvType.text = "\\"
                }
                3 -> {
                    tvAnswer.text = stuAnswer
                    val tvWidth = ToolsUtils.getViewWidth(tvAnswer)
                    val svWidth = dsv.width
                    tvAnswer.paint.flags = Paint.UNDERLINE_TEXT_FLAG
                    val RalX = x + width + DensityUtils.dp2px(requireActivity(), 20f)
                    if (RalX + tvWidth > svWidth) {
                        tvAnswer.x = svWidth - tvWidth - 10.toFloat()
                    } else {
                        tvAnswer.x = RalX
                    }
                    tvAnswer.y = y + DensityUtils.dp2px(getActivity(), 5f)
                    tvType.gravity = Gravity.END
                    tvType.text = "/"
                }
            }
        }
    }

}